package com.example.shoppingmallclient.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.shoppingmallclient.R;
import com.example.shoppingmallclient.ServerIp;
import com.example.shoppingmallclient.activity.ShowProductDetail;
import com.example.shoppingmallclient.adapter.CartListAdapter;
import com.example.shoppingmallclient.vo.CartItemVo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


/**
 * @author 袁梦达 2019012364
 */
public class FragmentThird extends Fragment {

    private List<CartItemVo> list;
    private String cartTotalPrice;
    private TextView tvCartTotalPrice;
    private ListView listView;
    private Button submitOrder;
    private CartListAdapter cartListAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.cart_list, container, false);
        tvCartTotalPrice = view.findViewById(R.id.tv_cart_total_price);
        list = new ArrayList<>();
        listView = view.findViewById(R.id.lv);
        submitOrder = view.findViewById(R.id.submit_order);

        new getCartList().execute();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), ShowProductDetail.class);
                intent.putExtra("productId", list.get(position).getProductId());
                startActivity(intent);
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                cartTotalPrice = String.valueOf(Double.parseDouble(cartTotalPrice) - list.get(position).getSumPrice());
                new removeProductFromCart().execute(list.get(position).getProductId());
                list.remove(list.get(position));
                return true;
            }
        });

        submitOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new submitOrder().execute();
            }
        });

        return view;
    }

    private class removeProductFromCart extends AsyncTask<Integer, Object, String> {

        @Override
        protected String doInBackground(Integer... productId) {
            String result = null;
            try {
                String serverUrl = "http://" + ServerIp.ServerIp + ":8080/CartServlet";
                URL url = new URL(serverUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                OutputStream os = connection.getOutputStream();

                String msg = "remove," + productId[0];
                os.write(msg.getBytes());
                os.flush(); //刷新缓存

                //接收服务器发来的消息
                InputStream is = connection.getInputStream();
                StringBuffer stringBuffer = new StringBuffer();
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = is.read(bytes)) != -1) {
                    stringBuffer.append(new String(bytes, 0, len));
                }
                result = stringBuffer.toString();
                System.out.println(result);
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            if("true".equals(result)){
                Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(getContext(), "删除失败", Toast.LENGTH_SHORT).show();
            }
            tvCartTotalPrice.setText("总价：￥" + cartTotalPrice);
            cartListAdapter.notifyDataSetChanged();
        }
    }

    private class submitOrder extends AsyncTask{
        @Override
        protected Object doInBackground(Object[] objects) {
            String result = null;
            try {
                System.out.println(111);
                String serverUrl = "http://" + ServerIp.ServerIp + ":8080/OrderServlet";
                URL url = new URL(serverUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");

                InputStream is = connection.getInputStream();
                System.out.println(222);
                StringBuffer stringBuffer = new StringBuffer();
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = is.read(bytes)) != -1){
                    stringBuffer.append(new String(bytes, 0, len));
                }

                result = stringBuffer.toString();
                list.clear();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(Object result) {
            if("true".equals(result)){
                Toast.makeText(getContext(), "下单成功！", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(getContext(), "下单失败！", Toast.LENGTH_SHORT).show();
            }
            cartListAdapter.notifyDataSetChanged();
            tvCartTotalPrice.setText("总价：￥0");
        }
    }

    private class getCartList extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] objects) {
            try {
                String serverUrl = "http://" + ServerIp.ServerIp + ":8080/CartShowServlet";
                URL url = new URL(serverUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");

                InputStream is = connection.getInputStream();
                StringBuffer stringBuffer = new StringBuffer();
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = is.read(bytes)) != -1){
                    stringBuffer.append(new String(bytes, 0, len));
                }

                String substring = null;
                if(stringBuffer.toString().length() > 1){
                    substring = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
                }
                String[] strings = substring.split("#");

                cartTotalPrice = strings[0];
                System.out.println(cartTotalPrice);
                for(int i = 1; i < strings.length; i++){
                    String[] split = strings[i].split("@");

                    String image = split[0];
                    URL imgUrl = new URL(image);
                    InputStream inputStream = imgUrl.openStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                    CartItemVo cartItemVo = new CartItemVo();
                    cartItemVo.setImage(bitmap);
                    cartItemVo.setBaseInformation(split[1]);
                    cartItemVo.setPrice(Double.parseDouble(split[2]));
                    cartItemVo.setQuantity(Integer.valueOf(split[3]));
                    cartItemVo.setSumPrice(Double.parseDouble(split[4]));
                    cartItemVo.setProductId(Integer.valueOf(split[5]));
                    list.add(cartItemVo);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            tvCartTotalPrice.setText("总价：￥" + cartTotalPrice);
            cartListAdapter = new CartListAdapter(list, R.layout.cart_item, getContext());
            listView.setAdapter(cartListAdapter);
        }
    }
}
